package vip.fuxk.blog.front;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import org.noear.luffy.executor.ExecutorFactory;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;
import vip.fuxk.blog.config.FuckHandler;
import vip.fuxk.blog.utils.PropKit;

import java.io.PrintWriter;
import java.io.StringWriter;

@Controller
public class CommonErrorController {



    @Mapping("/404")
    public void page404(Context ctx ) throws Exception {
        ctx.pathNew(PropKit.getCodePath()+"404.ftl");
        this.handle(ctx);
    }

    public void uiAssects(Context ctx,String end) throws Exception{
        String codePath = PropKit.getCodePath();
        String adminThemePath = end.equals("/admin/")? PropKit.getAdminThemePath():PropKit.getFrontThemePath();
        String path = ctx.path();
        if(StrUtil.count(path,'/') ==1 && !path.endsWith("/") && ObjUtil.isEmpty(FileNameUtil.getSuffix(path))){
            path = path.concat("/");
        }
        String lastPath = path.replaceAll("^"+end.replaceAll("\\/","\\\\/"),"") ;
        String endPath = codePath.concat(adminThemePath).concat(lastPath);
        ctx.pathNew(endPath);
        this.handle(ctx);
    }

    public void handle(Context ctx) throws Exception {
        Solon.cfg().getBean(FuckHandler.class)
                .handle(ctx);
    }

    @Mapping(value = "/admin/**")
    public void adminAssects(Context ctx ) throws Exception {
        this.uiAssects(ctx,"/admin/");
    }
    @Mapping(value = "/admin")
    public void adminAssect(Context ctx ) throws Exception {
        this.uiAssects(ctx,"/admin/");
    }

    @Mapping(value = "/front/**")
    public void frontAssects(Context ctx ) throws Exception {
        this.uiAssects(ctx,"/front/");
    }
    @Mapping(value = "/front")
    public void frontAssect(Context ctx ) throws Exception {
        this.uiAssects(ctx,"/front/");
    }





}
